<?php 
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

class ScoopitDatabase {

	private $table_name;
	private $user_id;
	private $platform;
	private $db;
	
	function __construct() {
		global $wpdb;
		$this->db = $wpdb;
		$this->table_name = $this->db->prefix . "shareOn";
	}
		
	public static function createTable() {
		global $wpdb;
		$table_name = $wpdb->prefix . "shareOn";
		$sql = "CREATE TABLE IF NOT EXISTS $table_name (
				user_id BIGINT,
				PRIMARY KEY(user_id),
				platform varchar(255),
				access_token longtext,
				secret longtext,
				shareto longtext
				)";
		
		dbDelta($sql);
	}
	
	public static function deleteTable() {
		global $wpdb;
		$table_name = $wpdb->prefix . "shareOn";
		$sql = "DROP TABLE IF EXISTS $table_name";
		$wpdb->query($sql);
		dbDelta($sql);
	}
	
	function selectUserAndPlatform($user_id, $platform) {
		$this->user_id = $user_id;
		$this->platform = $platform;
		$this->insertRow();
	}
	
	function insertRow() {
		$sql = "INSERT INTO $this->table_name (user_id, platform, access_token, secret, shareto) VALUES ('$this->user_id', '$this->platform', null, null, null) ON DUPLICATE KEY UPDATE user_id = $this->user_id";
		dbDelta($sql);
	}
	
	function setAccessToken($access_token) {
		$sql = "UPDATE $this->table_name SET access_token = '$access_token' WHERE user_id = $this->user_id AND platform = '$this->platform'";
		$this->db->query($sql);	
	}
		
	function setSecret($secret) {
		$sql = "UPDATE $this->table_name SET secret = '$secret' WHERE user_id = $this->user_id AND platform = '$this->platform'";
		$this->db->query($sql);
	}
	
	function getAccessToken() {
		$sql = "SELECT access_token FROM $this->table_name WHERE user_id = $this->user_id AND platform = '$this->platform'";
		$row = $this->db->get_row($sql, ARRAY_A);
		return $row['access_token'];
	}
	
	function getSecret() {
		$sql = "SELECT secret FROM $this->table_name WHERE user_id = $this->user_id AND platform = '$this->platform'";
		$row = $this->db->get_row($sql, ARRAY_A);
		return $row['secret'];
	}
	
	function setSharers($sharers) {
		$sql = "UPDATE $this->table_name SET shareto = '$sharers' WHERE user_id = $this->user_id AND platform = '$this->platform'";
		$this->db->query($sql);	
	}
	
	function getSharers() {
		$sql = "SELECT shareto FROM $this->table_name WHERE user_id = $this->user_id AND platform = '$this->platform'";
		$row = $this->db->get_row($sql, ARRAY_A);
		return $row['shareto'];
	}
	
	function emptySharers() {
		$sql = "UPDATE $this->table_name SET shareto = null WHERE user_id = $this->user_id AND platform = '$this->platform'";
		$this->db->query($sql);	
	}
}
?>